﻿// -----------------------------
// Copyright © Kodi Studios 2012
// -----------------------------

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;

namespace Kodi.Picturethrill
{
    /// <summary>
    /// Interaction logic for PictureSiteName.xaml
    /// </summary>
    public partial class ImagePreviewControl : UserControl
    {
        #region Private Fields
        private string imagePath = string.Empty;
        private MainWindow mainWindow;
        private IImageProvider imageProvider;
        #endregion

        #region Constructors
        public ImagePreviewControl(MainWindow mainWindow, IImageProvider imageProvider)
        {
            this.mainWindow = mainWindow;
            this.imageProvider = imageProvider;

            InitializeComponent();

            this.ProviderName = imageProvider.Name;
            this.Url = imageProvider.SiteName;
        }
        #endregion

        #region Public Events
        public event RoutedEventHandler Checked;
        public event Action<ImagePreviewControl> PreviewImageUpdated;
        #endregion

        #region Public Properties
        public string ImagePath
        {
            get
            {
                return this.imagePath;
            }
            set
            {
                this.imagePath = value;

                // TODO: figure out whether cleaning streams is needed
                //if (string.IsNullOrEmpty(this.imagePath))
                //{
                //    // Remove existing image
                //    BitmapImage bitmapImage = this.previewImage.Source as BitmapImage;
                //    if (bitmapImage != null)
                //    {
                //        MemoryStream memoryStream = bitmapImage.StreamSource as MemoryStream;
                //        if (memoryStream != null)
                //        {
                //            memoryStream.Dispose();
                //        }
                //        bitmapImage.StreamSource = null;
                //    }
                //    this.previewImage.Source = null;
                //}

                // these should be events :)
                if (!string.IsNullOrEmpty(this.imagePath) &&
                    File.Exists(this.imagePath))
                {
                    try
                    {
                        MemoryStream stream = new MemoryStream();

                        Bitmap bitmapFull = new Bitmap(this.imagePath);  // Create new Bitmap (System.Drawing.Bitmap) from the existing image file
                        int minWidthHeight = Math.Min(bitmapFull.Size.Width, bitmapFull.Size.Height);
                        Bitmap bitmap = CropBitmap(bitmapFull, (bitmapFull.Size.Width - minWidthHeight) / 2, (bitmapFull.Size.Height - minWidthHeight) / 2, minWidthHeight, minWidthHeight);
                        bitmap.Save(stream, ImageFormat.Png);

                        this.Dispatcher.Invoke((ThreadStart)delegate
                            {
                                // Create preview image
                                BitmapImage previewBitmapImage = new BitmapImage();
                                previewBitmapImage.BeginInit();
                                previewBitmapImage.DecodePixelHeight = 64;
                                previewBitmapImage.StreamSource = stream;
                                previewBitmapImage.EndInit();
                                this.previewImage.Source = previewBitmapImage;
                            });

                        // Notify that preview image has been updated
                        if (this.PreviewImageUpdated != null)
                        {
                            this.PreviewImageUpdated(this);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Comment(e.ToString());
                    }
                }
            }
        }

        private static Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
        {
            Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
            Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
            return cropped;
        }

        public string Url
        {
            get
            {
                return (string)this.urlLabel.Content;
            }
            internal set
            {
                this.urlLabel.Content = value;
            }
        }

        public IImageProvider ImageProvider
        {
            get
            {
                return this.imageProvider;
            }
        }

        /// <summary>
        /// Image provider name.
        /// </summary>
        public string ProviderName
        {
            get
            {
                return (string)this.nameLabel.Content;
            }
            internal set
            {
                this.nameLabel.Content = value;
            }
        }

        public bool IsChecked
        {
            get
            {
                return (bool)this.previewRadioButton.IsChecked;
            }
            set
            {
                this.previewRadioButton.IsChecked = value;
            }
        }
        #endregion

        #region Event Handlers

        private void OnUserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            using (Log.Group())
            {
                mainWindow.SetWallpaperAndSave(this.imageProvider);
            }
        }

        private void OnPreviewRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            using (Log.Group())
            {
                if (this.Checked != null)
                {
                    this.Checked(this, e);
                }
            }
        }

        #endregion
    }
}
